/**
 * 
 */
package com.hb.util;

/**
 * @author Pham Hong Hung
 *
 */

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.i18n.LocaleContextHolder;

import com.hb.Constants;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public final class DateUtil {
    private static Log log = LogFactory.getLog(DateUtil.class);
    private static final String TIME_PATTERN = "HH:mm";
    
    public static final String HH_mm = "HH:mm";
    public static final String yyyy_MM_dd = "yyyy-MM-dd";
    public static final String yyyy_Slash_MM_Slash_dd = "yyyy/MM/dd";
    public static final String dd_Slash_MM_Slash_yyyy = "dd/MM/yyyy";
    public static final String E_d_MMM_yyyy = "E, d MMM yyyy";
    public static final String yyyy_MM_dd_hh_mm_ss = "yyyy-MM-dd H.mm.ss";
    /**
     * Checkstyle rule: utility classes should not have public constructor
     */
    private DateUtil() {
    }

    public static Boolean areDatesOnTheSameDay(Date date1, Date date2){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	String sd1 = sdf.format(date1);
    	String sd2 = sdf.format(date2);
    	if(sd1.equals(sd2))
    		return true;
    	else
    		return false;
    }

    public static Integer getDaysInMonth(Integer month){
		Calendar calendar = Calendar.getInstance();
		int year = 2008;
		int date = 1;
		calendar.set(year, month, date);
		int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

		return days;
    }

    public static Integer getDayInMonth(Date date){
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(date);
    	return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * adds one day to the date passed in.
     * @param date
     * @return returns a new date with day+1
     */
    public static Date addOneDay(Date date){

    	return addDaysToDate(date,1);
    }

    public static Date addDaysToDate(Date date, int daysToAdd){
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
    	cal.add(Calendar.DAY_OF_MONTH, daysToAdd);
    	return cal.getTime();
    }

    public static Date addMinutesToDate(Date date, int minutesToAdd){
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(date);
    	cal.add(Calendar.MINUTE, minutesToAdd);
    	
    	return cal.getTime();
    }
    

    /**
     * Return default datePattern (MM/dd/yyyy)
     *
     * @return a string representing the date pattern on the UI
     */
    public static String getDatePattern() {
        Locale locale = LocaleContextHolder.getLocale();
        String defaultDatePattern;
        try {
            defaultDatePattern = ResourceBundle.getBundle(Constants.BUNDLE_KEY, locale)
                    .getString("date.format");
        } catch (MissingResourceException mse) {
            defaultDatePattern = "MM/dd/yyyy";
        }

        return defaultDatePattern;
    }

    public static String getDateTimePattern() {
        return DateUtil.getDatePattern() + " HH:mm:ss.S";
    }

    /**
     * This method attempts to convert an Oracle-formatted date
     * in the form dd-MMM-yyyy to mm/dd/yyyy.
     *
     * @param aDate date from database as a string
     * @return formatted string for the ui
     */
    public static String getDate(Date aDate) {
        SimpleDateFormat df;
        String returnValue = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param strDate a string representation of a date
     * @return a converted Date object
     * @throws ParseException when String doesn't match the expected format
     * @see java.text.SimpleDateFormat
     */
    public static Date convertStringToDate(String aMask, String strDate)
            throws ParseException {
        SimpleDateFormat df;
        Date date;
        df = new SimpleDateFormat(aMask);

        if (log.isDebugEnabled()) {
            log.debug("converting '" + strDate + "' to date with mask '" + aMask + "'");
        }

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            //log.error("ParseException: " + pe);
            throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }

        return (date);
    }

    /**
     * This method returns the current date time in the format:
     * MM/dd/yyyy HH:MM a
     *
     * @param theTime the current time
     * @return the current date/time
     */
    public static String getTimeNow(Date theTime) {
        return getDateTime(TIME_PATTERN, theTime);
    }


    /**
     *
     * @return the date with all fields init to the current time d/m/y h:m:s
     */
    public static Date getTimeNow(){
    	return Calendar.getInstance().getTime();
    }

    /**
     * This method returns the current date in the format: MM/dd/yyyy
     *
     * @return the current date
     * @throws ParseException when String doesn't match the expected format
     */
    public static Calendar getToday() throws ParseException {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(getDatePattern());

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));

        return cal;
    }
    
    /**
     * This method returns the current date in the format: datePattern
     *
     * @return the current date
     * @throws ParseException when String doesn't match the expected format
     */
    public static Calendar getToday(String datePattern) throws ParseException {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(datePattern);

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(datePattern, todayAsString));

        return cal;
    }

    /**
     * This method generates a string representation of a date's date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * @see java.text.SimpleDateFormat
     */
    public static String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
            log.warn("aDate is null!");
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date based
     * on the System Property 'dateFormat'
     * in the format you specify on input
     *
     * @param aDate A date to convert
     * @return a string representation of the date
     */
    public static String convertDateToString(Date aDate) {
        return getDateTime(getDatePattern(), aDate);
    }

    public static String convertDateToString(String aMask, Date aDate) {
        return getDateTime(aMask, aDate);
    }

    /**
     * This method converts a String to a date using the datePattern
     *
     * @param strDate the date to convert (in format MM/dd/yyyy)
     * @return a date object
     * @throws ParseException when String doesn't match the expected format
     */
    public static Date convertStringToDate(final String strDate) throws ParseException {
        return convertStringToDate(getDatePattern(), strDate);
    }

    /**
     *
     * @return the current time instance as a Date object
     */
    public static Date getCurrentDate(){
    	return Calendar.getInstance().getTime();
    }

    /**
     * returns the difference in dates based on the measureUnit (which uses Calendar contants).
     * If measure unit does not exist as a value in Calendar, then the difference defaults to days
     * @param earlierDate
     * @param laterDate
     * @param measureUnit
     * @return
     */
	public static Long getDifference(Date earlierDate, Date laterDate,Integer measureUnit){
		Long earlierMilis = earlierDate.getTime();
		Long laterMilis = laterDate.getTime();

		long diff = laterMilis - earlierMilis;

		switch(measureUnit){
			case Calendar.DAY_OF_MONTH:
				return (diff / (1000 * 60 * 60 * 24));

			case Calendar.HOUR:
			case Calendar.HOUR_OF_DAY:
				return (diff / (1000 * 60 * 60));

			case Calendar.MINUTE:
				return (diff / (1000 * 60));

			case Calendar.SECOND:
				return (diff / (1000));

			case Calendar.MILLISECOND:
				return (diff);
			default:
				return (diff / (1000 * 60 * 60 * 24));
		}
	}
	 public static Integer compareDateOnFormat(Date date1, Date date2, String dateFormat){
    	 SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    	 
    	 String formatDate1 = null, formatDate2 = null;
		 formatDate1 = sdf.format(date1);
		 formatDate2 = sdf.format(date2);
    	
    	 if(formatDate1.compareTo(formatDate2) > 0){
     		return 1;
     	 }else if(formatDate1.compareTo(formatDate2) < 0){
     		return -1;
     	 }else if(formatDate1.compareTo(formatDate2) == 0){
     		return 0;
     	 }else{
     		return -1;
     	 }
		
    	 
     }
	 
	 public static Date getDateInFormat(Date date, String format){
		 
		 if(date == null || StringUtils.isBlank(format)){
			 return null;
		 }
		 SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		 String formattedDate = dateFormat.format(date);
		 
		 try {
			return dateFormat.parse(formattedDate);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	 }
}
